package com.hxzy.controller.unit;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.util.BeanValidatorUtil;
import com.hxzy.util.ThreadLocalUtil;
import com.hxzy.common.BaseServlet;
import com.hxzy.common.ResultAjax;
import com.hxzy.entity.Unit;
import com.hxzy.service.UnitService;
import com.hxzy.service.impl.UnitServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;

/**
 * @Author: lqq
 * @Description:
 * @Date: 2022/3/8 16:20
 */
@WebServlet(urlPatterns = "/unit/add")
public class AddUnitServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        resp.setCharacterEncoding("UTF-8");
        ThreadLocalUtil.threadLocal.get();
        try {

            //搜集参数
            Unit unit = super.CollectiongParameterVlues(req, Unit.class);
            unit.setId(UUID.randomUUID().toString().replace("-",""));
            //验证参数
            Set<String> validator = BeanValidatorUtil.validator(Unit.class, unit);
            //验证通过
            if (validator.isEmpty()){
                UnitService unitServlet=new UnitServiceImpl();
                int insert = unitServlet.insert(unit);
                ResultAjax resultAjax=null;
                if (insert>0){
                    resultAjax=ResultAjax.success("加入成功");
                }else {
                    resultAjax=ResultAjax.success("加入失败");
                }
                super.render(resp, JSONObject.toJSONString(resultAjax));
            }else {
                String next = validator.iterator().next();
                ResultAjax error = ResultAjax.error(next);
                super.render(resp, JSONObject.toJSONString(error));
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    }

